package com.itlong.cloud.commons.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.property.CloudElevatorIotCallCtrlMessageDTO;
import com.itlong.cloud.POJO.DTO.property.CloudElevatorIotCallCtrlV10XMessageDTO;
import com.itlong.cloud.POJO.PO.SendCallElevatorMessageTaskPO;
import com.itlong.cloud.app.dao.IAppDeviceDao;
import com.itlong.cloud.commons.service.ISendIotCallElevatorService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.CloudElevatorIotOrderTypeEnum;
import com.itlong.cloud.enumerate.DeviceIotEnum;
import com.itlong.cloud.enumerate.IotCloudCtrlInstructEnum;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SendIotCallElevatorServiceImpl implements ISendIotCallElevatorService {

    private static final Logger LOG = LoggerFactory.getLogger(SendIotCallElevatorServiceImpl.class);

    @Autowired
    MessageSender messageSender;

    @Autowired
    RedisService redisService;

    @Autowired
    IAppDeviceDao iAppDeviceDao;

    @Override
    public boolean send(SendCallElevatorMessageTaskPO send) {
        try {
            String deviceUnique = send.getDeviceUnique();
            List<Map<String, Object>> controls = new ArrayList<>();
            Integer deviceType = StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique);
            String v = send.getVersion();
            if (StringUtils.isBlank(v) || Integer.valueOf(v.substring(v.indexOf("V") + 1, v.indexOf("V") + 5)) < 1040) {
                //遍历需要发布控制指令的电梯并发布消息
                CloudElevatorIotCallCtrlMessageDTO message = new CloudElevatorIotCallCtrlMessageDTO();
                message.setSourceFrom(send.getSourceFrom());
                //外呼指令
                if (send.getOutData() != null && send.getOutData().size() > 0) {
                    Map<String, Object> out = new HashMap<>();
                    out.put("cmdVer", "0");
                    ArrayList<Map<String, Object>> t = new ArrayList<>();
                    t.add(send.getOutData());
                    out.put("data", t);
                    message.setOut(out);
                }
                //内呼指令
                if (send.getInData() != null && send.getInData().size() > 0) {
                    Map<String, Object> in = new HashMap<>();
                    in.put("cmdVer", "0");
                    ArrayList<Map<String, Object>> t = new ArrayList<>();
                    t.add(send.getInData());
                    in.put("data", t);
                    message.setIn(in);
                }
                //发送电梯控制指令
                Map<String, Object> control = new HashMap<>();
                control.put("productKey", send.getIotProductKey());
                control.put("message", JsonUtil.toJSON(message));
                control.put("topic", "/" + (deviceType == 5 ? deviceUnique + "/user" : deviceUnique) + IotCloudCtrlInstructEnum.DEVICECTRL.getUrl());
                controls.add(control);
            } else {
                CloudElevatorIotCallCtrlV10XMessageDTO message = new CloudElevatorIotCallCtrlV10XMessageDTO();
                message.setCmd(CloudElevatorIotOrderTypeEnum.FIXEDAMOUNT.getType());//1003
                message.setSourceFrom(send.getSourceFrom());
                message.setSnr(send.getSnr());
                message.setTimestamp((new Date()).getTime() + "");
                Map<String, Object> messageDataChild = new JSONObject();
                //外呼指令
                if (send.getOutData() != null && send.getOutData().size() > 0) {
                    Map<String, Object> out = new HashMap<>();
                    out.put("cmdVer", "0");
                    ArrayList<Map<String, Object>> t = new ArrayList<>();
                    t.add(send.getOutData());
                    out.put("data", t);
                    messageDataChild.put("out", out);
                }
                //内呼指令
                if (send.getInData() != null && send.getInData().size() > 0) {
                    Map<String, Object> in = new HashMap<>();
                    in.put("cmdVer", "0");
                    ArrayList<Map<String, Object>> t = new ArrayList<>();
                    t.add(send.getInData());
                    in.put("data", t);
                    messageDataChild.put("in", in);
                }
                message.setData(messageDataChild);
                //发送电梯控制指令
                Integer sendVersion = null;
                if (deviceType == 1) {
                    String sv = StringHandlerUtil.getNullOrStringForObject(redisService.get(RedisConstant.ELEVATOR_PRODUCT_VERSION_REDIS_KEY));
                    if (StringUtils.isNotBlank(sv)) {
                        sendVersion = Integer.valueOf(sv);
                    } else {
                        sendVersion = iAppDeviceDao.getElevatorProductVersion();
                        redisService.set(RedisConstant.ELEVATOR_PRODUCT_VERSION_REDIS_KEY, RedisConstant.ELEVATOR_PRODUCT_VERSION_CACHE_TIME, sendVersion);
                    }
                }
                Map<String, Object> control = new HashMap<>();
                control.put("productKey", send.getIotProductKey());
                control.put("message", JsonUtil.toJSON(message));
                control.put("topic", "/" + (deviceType == 5 || (sendVersion != null && sendVersion == 1) ? deviceUnique + "/user" : deviceUnique) + IotCloudCtrlInstructEnum.DEVICECMD.getUrl());
                controls.add(control);
            }
            //
            Map<String, Object> params = new HashMap<>();
            params.put("deviceOperateIotType", DeviceIotEnum.PUB_MESSAGE.getCommandType());
            params.put("devices", controls);
            params.put("timestamp", (new Date()).getTime());
            JSONObject obj = new JSONObject();
            obj.put("data", params);
            messageSender.send(RabbitMQConstant.RABBITMQ_IOT_PUB_QUEUE, obj.toJSONString(), RabbitMQConstant.RABBITMQ_IOT_PUB_EXCHANGE, RabbitMQConstant.RABBITMQ_IOT_PUB_KEY);
        } catch (Exception e) {
            LOG.error("【发送呼梯消息数据异常】", e);
            return false;
        }
        return true;
    }

}